package com.sq.partner.manager.util;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.log4j.Logger;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FreeMarkerUtil {
	private static Logger logger = Logger.getLogger(FreeMarkerUtil.class);
	private static Configuration configuration = null;
	static boolean isInited = false;
	
	/**
	 * 初使化方法  web容器初使化调用
	 * @param servletContext
	 */
	public static void init(ServletContext servletContext){
		configuration = new Configuration();
		configuration.setServletContextForTemplateLoading(servletContext, "/WEB-INF/templates");
		configuration.setDateFormat("yyyy-MM-dd");
		configuration.setDateTimeFormat("yyyy-MM-dd HH:mm:ss");
		configuration.setDefaultEncoding("UTF-8");
		isInited = true;
		logger.info("FreeMarker引擎加载成功！");
	}
	
	/**
	 * 返回转换后的对像，出错返回空串
	 * @param templateName 模板名  需在 WEB-INF/templates下 如  test.ftl
	 * @param dataModel 数据
	 * @return
	 * @throws IOException 
	 * @throws TemplateException 
	 * @throws AppException 
	 */
	public static String process(String templateName,Map<String,?> dataModel) throws TemplateException, IOException, Exception{
		if(!isInited){
			throw new Exception("模板引擎尚未初使化，请检查是否web环境或配置信息。");
		}
		Template template = configuration.getTemplate(templateName);
		StringWriter stringWriter = new StringWriter();
		template.process(dataModel, stringWriter);
		return stringWriter.toString();
	}
	
}
